<template>
  <div class="chart-container" ref="chartContainer"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  data: {
    type: Array,
    required: true
  }
});

const chartContainer = ref(null);
let chart = null;

const initChart = () => {
  if (!chartContainer.value) return;
  
  chart = echarts.init(chartContainer.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      top: '10%',
      left: '3%',
      right: '10%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: '#7fdbff',
        formatter: (value) => {
          return value + '人';
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: props.data.map(item => item.name),
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: '#7fdbff'
      }
    },
    series: [
      {
        type: 'bar',
        data: props.data.map(item => ({
          value: item.value,
          itemStyle: {
            color: getDensityColor(item.density)
          }
        })),
        barWidth: '60%',
        label: {
          show: true,
          position: 'right',
          color: '#fff',
          formatter: '{c}人'
        }
      }
    ],
    visualMap: {
      show: false,
      min: 0,
      max: 1000,
      inRange: {
        color: ['#00e473', '#ffc107', '#ff9800', '#ff4757']
      }
    }
  };
  
  chart.setOption(option);
};

const getDensityColor = (density) => {
  switch (density) {
    case '舒适': return '#00e473';
    case '中等': return '#ffc107';
    case '较高': return '#ff9800';
    case '拥挤': return '#ff4757';
    default: return '#00e473';
  }
};

const handleResize = () => {
  chart?.resize();
};

watch(() => props.data, () => {
  initChart();
}, { deep: true });

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  chart?.dispose();
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 200px;
  background: rgba(0, 20, 40, 0.15);
  border-radius: 6px;
  backdrop-filter: blur(2px);
  border: 1px solid rgba(0, 195, 255, 0.1);
}
</style> 